<template>
  <page-header-wrapper :title="false">
    <div class="Role">
      <a-spin tip="加载中..." class="position" v-if="roleLoading"> </a-spin>
      <a-modal
        width="45%"
        v-model="modleVisible"
        :title="form.id ? '编辑安全模板' : '新增安全模板'"
        @cancel="() => (this.modleVisible = false)"
        :confirm-loading="formButtonDisableFlag"
        @ok="onSubmit"
      >
        <div id="modalContent">
          <div class="formAspin" v-if="editWaitForLoading">
            <a-spin />
          </div>
          <div class="modalContentForm">
            <a-form-model
              ref="formRef"
              :model="form"
              :rules="rules"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 18 }"
            >
              <a-row type="flex" justify="space-between">
                <a-col :span="12">
                  <Input
                    :form="form"
                    label="模版名称"
                    prop="title"
                    placeholder="请输入模版名称"
                  ></Input>
                </a-col>
                <a-col :span="12">
                  <Input
                    :form="form"
                    label="用户名"
                    prop="loginName"
                    placeholder="请输入用户名"
                  ></Input>
                </a-col>
                <a-col :span="12">
                  <Input
                    :form="form"
                    label="密码"
                    prop="loginPass"
                    placeholder="请输入密码"
                  ></Input>
                </a-col>
                <a-col :span="12">
                  <Input
                    :form="form"
                    label="密钥"
                    prop="aesKey"
                    placeholder="请输入密钥"
                  ></Input>
                </a-col>
              </a-row>
            </a-form-model>
          </div>
        </div>
      </a-modal>
      <typicalSearch ref="insideSearch" :searchConfig="searchConfig" @searchMethod="getTableData"></typicalSearch>
      <div class="table">
        <div class="tableTitle">
          <div class="title">安全模板管理</div>
          <div class="addButton">
            <a-button type="primary" @click="handleEdit()">
              新增安全模板
            </a-button>
          </div>
        </div>
        <div class="tableList">
          <typicalTable ref="insideTable" :tableConfig="tableConfig" :tableData="tableData" @getTableData="getTableData">
            <template v-slot="slotProps">
              <Button label="编辑" @click="handleEdit(slotProps.record)"></Button>
              <a-popconfirm
                slot="action"
                title="此操作将删除该条数据，是否继续?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(slotProps.record)"
              >
                <Button type="stop" label="删除"></Button>
              </a-popconfirm>
            </template>
          </typicalTable>
        </div>
      </div>
    </div>
  </page-header-wrapper>
</template>
<script>
import {
  listCabinetSecurities,
  createCabinetSecurity,
  updateCabinetSecurity,
  loadCabinetSecurityById,
  deleteCabinetSecurityById
} from '@/api/api';
import moment from 'moment';
import typicalSearch from '@/components/typicalSearch';
import typicalTable from '@/components/typicalTable';
import Input from '@/components/typicalControl/Input';
import treeSelect from '@/components/typicalControl/treeSelect';
import Select from '@/components/typicalControl/select';
import Button from '@/components/typicalControl/button';
export default {
  name: 'UserTemplate',
  components: {
    typicalSearch: typicalSearch,
    typicalTable: typicalTable,
    Input: Input,
    treeSelect: treeSelect,
    Button: Button,
    Select: Select
  },
  data() {
    return {
      formButtonDisableFlag: false, // 表单确定禁用按钮 防止多次点击多次保存
      editWaitForLoading: false, // 加载编辑回显数据等待Loading
      roleLoading: false, // 加载表格的loading
      modleVisible: false, // 控制弹框
      form: {
        title: undefined,
        loginPass: undefined,
        isEnable: '1',
        isSystem: '0',
        loginName: undefined,
        aesKey: undefined
      },
      rules: {
        // 规则验证
        title: [
          { required: true, message: '请输入模板名称', trigger: 'blur' },
          { max: 15, message: '最大长度不能超过15个字', trigger: 'blur' }
        ],
        aesKey: [
          { required: true, message: '请输入密钥', trigger: 'blur' },
          { max: 45, message: '最大长度不能超过45个字', trigger: 'blur' }
        ],
        loginName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { max: 45, message: '最大长度不能超过45个字', trigger: 'blur' }
        ],
        loginPass: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { max: 45, message: '最大长度不能超过45个字', trigger: 'blur' }
        ]
      },
      // 搜索组件配置
      searchConfig: {
        formItemList: [
          {
            type: 'input',
            prop: 'searchTitle',
            value: '',
            label: '模板名称'
          },
          {
            type: 'input',
            prop: 'searchLoginName',
            value: '',
            label: '用户名'
          }
        ],
        parent: this
      },
      // 列表组件配置
      tableConfig: {
        columns: [
          {
            title: '模板名称',
            dataIndex: 'title',
            ellipsis: true
          },
          {
            title: '用户名',
            dataIndex: 'loginName',
            ellipsis: true
          },
          {
            title: '密码',
            dataIndex: 'loginPass',
            ellipsis: true
          },
          {
            title: '密钥',
            dataIndex: 'aesKey',
            ellipsis: true
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            customRender: this.formatterTime
          },
          {
            title: '创建人',
            dataIndex: 'createUser.name',
            ellipsis: true
          },
          {
            title: '操作',
            scopedSlots: { customRender: 'action' },
            ellipsis: true
          }
        ],
        pageSize: this.$store.state.user.defaultPaginationPagesize,
        pageSizeOptions: this.$store.state.user.defaultPaginationOptions,
        parent: this
      },
      // 列表组件数据
      tableData: {
        content: [],
        totalElements: 0
      }
    };
  },
  created() {
  },
  mounted() {
    this.$refs.insideSearch.searchInfo();
  },
  methods: {
    /**
     * [getTableData 获取表格数据]
     * @param  {[type]} searchParam [搜索条件]
     * @return {[type]}             [description]
     */
    getTableData(searchParam) {
      if (!searchParam) throw new Error('getTableData 没有入参搜索条件！');
      this.roleLoading = true;
      listCabinetSecurities(searchParam).then(res => {
        if (res.code == 200 && res.data.content) {
          this.tableData = res.data;
        } else {
          this.tableData.content = [];
          this.tableData.totalElements = 0;
        }
      }).finally(() => {
        this.roleLoading = false;
      });
    },
    /**
     * @description: 新增编辑安全模板表单提交
     */
    onSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.formButtonDisableFlag = true;
          if (this.form.id) {
            this.editRole(this.form);
          } else {
            this.roleAdd(this.form);
          }
        } else {
          return false;
        }
      });
    },

    /**
     * [initializationForm 初始化form数据]
     * @return {[type]} [description]
     */
    initializationForm() {
      return {
        title: undefined,
        loginPass: undefined,
        isEnable: '1',
        isSystem: '0',
        loginName: undefined,
        aesKey: undefined
      };
    },

    roleAdd(addRoleParam) {
      createCabinetSecurity({ body: addRoleParam })
        .then(res => {
          this.formSuccessOperation(res);
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },

    editRole(editRoleParam) {
      updateCabinetSecurity({ body: editRoleParam, id: editRoleParam.id })
        .then(res => {
          this.formSuccessOperation(res);
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },

    /**
     * @description: 表单新增编辑成功后的公共的代码 （消息提示 搜索框重置 请求表格数据）
     * @param {object} successFormData 表单请求成功后返回的对象
     */
    formSuccessOperation(successFormData) {
      this.$message.success(successFormData.message);
      this.modleVisible = false;
      this.$refs.insideTable.updateListData();
    },

    /**
     * [handleEdit 新增或编辑]
     * @param  {[type]} row [如果编辑入参行数据]
     * @return {[type]}     [description]
     */
    handleEdit(row) {
      this.modleVisible = true;
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.form = this.initializationForm();
      if (row) {
        this.editWaitForLoading = true;
        loadCabinetSecurityById({ id: row.id })
          .then(res => {
            if (res.code == 200) {
              this.form = Object.assign(this.form, res.data);
            }
          })
          .finally(() => {
            this.editWaitForLoading = false;
          });
      }
    },

    /**
     * @description: 点击删除
     * @param {object} row 格某一行的数据对象
     */
    handleDelete(row) {
      deleteCabinetSecurityById({ id: row.id }).then(res => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.$refs.insideTable.updateListData();
        }
      });
    },
    formatterTime(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '';
    }
  }
};
</script>

<style lang="less" scoped>
.Role {
  width: 100%;
  height: calc(100vh - 150px);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  .position {
    width: 100%;
    height: 100%;
    background: white;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  .table {
    flex: 1;
    background: white;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    .tableTitle {
      width: 100%;
      height: 64px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ececec;
      padding: 0 20px;
      margin-bottom: 10px;
      .title {
        width: 80%;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 550;
      }
      .addButton {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    .tableList {
      // max-height: calc(100vh - 380px);
      // overflow: auto;
      /deep/ .tableScroll {
        max-height: calc(100vh - 380px);
        overflow: auto;
      }
    }
  }
}
#modalContent {
  width: 100%;
  height: 200px;
  position: relative;
  .formAspin {
    position: absolute;
    width: 100%;
    height: 200px;
    background: #ececec;
    border-radius: 4px;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
